package com.negative.activities;

import java.io.FileNotFoundException;
import java.util.ArrayList;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.Session.StatusCallback;
import com.facebook.model.GraphObject;
import com.facebook.model.OpenGraphAction;
import com.facebook.model.OpenGraphObject;
import com.facebook.widget.FacebookDialog;
import com.negative.data.PurchaseData;
import com.negative.logic.DialogManager;
import com.negative.logic.MenuListener;
import com.negative.logic.PurchaseListAdapter;
import com.negative.utils.IOHelper;
import com.negative.utils.SharingManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;

public class PurchaseListActivity extends Activity {

	ListView purchaseList;
	Context context;
	ImageView menuButton;
	MenuListener menuListener;
	PurchaseListAdapter adapter;
	boolean toHome = false;
	private UiLifecycleHelper uiHelper;
	private boolean withFacebook = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.purchase_list_layout);
		toHome = this.getIntent().getBooleanExtra("toHome", false);

		initialize(savedInstanceState);

		final ArrayList<PurchaseData> purchases;
		try {
			purchases = IOHelper.ReadPurchases(this);

			adapter = new PurchaseListAdapter(this, purchases, withFacebook);
			purchaseList.setAdapter(adapter);
			purchaseList.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> adapter, View v,
						int position, long arg3) {
					PurchaseData data = (PurchaseData) v.getTag();
					if (data.getPurchaseNumber() != null) {
						Intent intent = new Intent(context,
								ETicketActivity.class);
						intent.putExtra("PurchaseData", data);
						startActivity(intent);
					} else {
						faildToCreateETicket();
					}
				}
			});
		} catch (Exception e) {
			// if there is no file we will leave the purchases list empty.
			if (e instanceof FileNotFoundException)
				return;
			DialogManager.showOKDialog(this, false, getString(R.string.error),
					getString(R.string.purchase_error));
		}
		SharingManager.setActivity(this);
	}

	private void initialize(Bundle savedInstanceState) {
		this.context = this;
		menuListener = new MenuListener(this);
		purchaseList = (ListView) findViewById(R.id.purchase_list_view);
		menuButton = (ImageView) findViewById(R.id.menu_icon);

		if (((NegativeApplication) context.getApplicationContext())
				.getEventList().isEmpty() == false) {
			menuButton.setOnClickListener(menuListener);
		}

		uiHelper = new UiLifecycleHelper(this, new StatusCallback() {

			@Override
			public void call(Session session, SessionState state,
					Exception exception) {
				// TODO Auto-generated method stub
				onSessionStateChange(session, state, exception);
			}
		});
		uiHelper.onCreate(savedInstanceState);
		
		try{
		    ApplicationInfo info = getPackageManager().
		            getApplicationInfo("com.facebook.katana", 0 );
		    withFacebook = true;
		} catch( PackageManager.NameNotFoundException e ){
		    withFacebook = false;
		}
	}

	public void faildToCreateETicket() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setMessage(R.string.eTicket_faild_to_create_error);
		alert.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent i = new Intent(context, MainMenu.class);
						startActivity(i);
						finish();
					}
				});
		alert.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		uiHelper.onActivityResult(requestCode, resultCode, data,
				new FacebookDialog.Callback() {
					@Override
					public void onError(FacebookDialog.PendingCall pendingCall,
							Exception error, Bundle data) {
						Log.e("Activity",
								String.format("Error: %s", error.toString()));

//						DialogManager.showOKDialog(
//								(PurchaseListActivity) context, true,
//								context.getString(R.string.error),
//								getString(R.string.facebook_error_message));
						AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(context);
					    dlgAlert.setMessage(context.getString(R.string.facebook_error_message));
					    dlgAlert.setTitle(context.getString(R.string.error));
					    dlgAlert.setPositiveButton("OK", null);
					    dlgAlert.setCancelable(true);
					    dlgAlert.create().show();
					}

					@Override
					public void onComplete(
							FacebookDialog.PendingCall pendingCall, Bundle data) {
						Log.i("Activity", "Success!");
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();
		SharingManager.setActivity(this);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
		SharingManager.setActivity(null);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
		SharingManager.setActivity(null);
	}

	public boolean createGraphDialog(String movieTitle) {
		try {
			OpenGraphObject video = OpenGraphObject.Factory
					.createForPost("video.other");
			video.setTitle(movieTitle);

			String imageURL = "https://lh5.ggpht.com/iE475cOi1IXnLC98Yj5xPfAAHb84TEU-gqMgFXeZ-dIn4TCRjJqj5Rzmc8R4cTSSkTE=w300-rw";
			ArrayList<String> images = new ArrayList<String>();
			images.add(imageURL);
			video.setImageUrls(images);

			OpenGraphAction action = GraphObject.Factory
					.create(OpenGraphAction.class);
			action.setProperty("video", video);
			action.setProperty("explicitly_shared", "true");
			action.setType("video.watches");

			FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(
					this, action, "video").build();
			uiHelper.trackPendingDialogCall(shareDialog.present());

			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (state.isOpened()) {
			Log.i("Session", "Logged in...");
		} else if (state.isClosed()) {
			Log.i("Session", "Logged out...");
		}
	}
}
